package wujinye.com.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import wujinye.com.dao.base.BaseDao;
import wujinye.com.model.Favorite;
import wujinye.com.utils.JDBCUtil;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class FavoriteDao extends BaseDao<Favorite> {
    /**
     * 根据用户ID，查找其关注的人，再从中找出关注文章的人的列表
     *
     * @param uId
     * @param id
     * @return
     */
    public List<Map<String, Object>> findCollectList(Integer uId, Integer id) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<Map<String, Object>> list = null;
        try {
            String sql = "select uf.user_focus_id as ufId,u.username,ui.real_name as realName \n" +
                    "from favorite f left join user_info ui on f.u_id = ui.user_id \n" +
                    "left join user_focus uf on f.u_id = uf.user_focus_id and uf.user_id = ?\n" +
                    "left join user u on uf.user_focus_id = u.id\n" +
                    "where f.a_id = ? and f.u_id <> ?;";
            list = qr.query(sql, new MapListHandler(), uId, id, uId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查找数据库中用户是否已经收藏文章
     *
     * @param uId
     * @param aId
     * @return
     */
    public Integer isCollect(Integer uId, Integer aId) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        Integer query = 0;
        try {
            String sql = "select * from favorite f where f.u_id = ? and f.a_id = ? limit 1;";
            query = qr.query(sql, new ScalarHandler<Integer>(), uId, aId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 用户取消收藏文章
     *
     * @param uId
     * @param aId
     */
    public void removeCollect(Integer uId, Integer aId) {
        String sql = "delete from favorite where u_id = ? and a_id = ?;";
        Object[] obj = {uId, aId};
        adu(sql, obj);
    }


    /**
     * 用户添加收藏文章
     *
     * @param uId
     * @param aId
     */
    public void addCollect(Integer uId, Integer aId) {
        String sql = "insert into favorite values(?,?,?)";
        Object[] obj = {null, uId, aId};
        adu(sql, obj);
    }
}
